<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
/**
 * 公众号服务器配置
 * @author chaituan@126.com
 */
use EasyWeChat\Foundation\Application;
class Notify extends CI_Controller {
	
	public function index() {
		$options = ['app_id' => WX_APPID1,'secret' => WX_APPSecret1,'token'  => 'ctfanqie'];
		$app = new Application($options);
		$server = $app->server;
		$server->setMessageHandler(function($message) use (&$app){
			switch ($message->MsgType) {
				case 'event':
					$openid = $message->FromUserName;
					
					if($message->Event == "subscribe"){
						$content = $openid;
					}elseif($message->Event == "SCAN"){
						$content = $openid;
					}
					
					
					break;
				case 'text':
					$openid = $message->FromUserName;
					$res = $app->user->get($openid);
					$content = $res->unionid;
					
					return $content;
					break;
				default:
					$content = '';
					break;
			}
			return $content;
		});
		$server->serve()->send();
	}
	
	public function pay(){
		$options = ['app_id'=>WX_APPID,'secret'=>WX_APPSecret,'payment' => ['merchant_id'=> WX_MCHID,'key'=> WX_KEY,'cert_path'=> SSLCERT_PATH,'key_path'=> SSLKEY_PATH,'notify_url'=> NOTIFY_URL]];
		$app = new Application($options);
		$response = $app->payment->handleNotify(function($notify, $successful){
			if($successful){
				$this->load->model(array('admin/User_model','admin/Order_model','admin/Integral_model','admin/Goods_model'));
				$order_arr = json_decode($notify,true);
				if($order_arr){
					$total = $order_arr['total_fee']/100;
					$order_no = $order_arr['out_trade_no'];
					$time = strtotime($order_arr['time_end']);
					$item = $this->Order_model->getItem(array('oid'=>$order_no,'state'=>1));
					if($item){
						$data = array('state'=>2,'paytime'=>$time,'transaction_id'=>$order_arr['transaction_id'],'pay_price'=>$total);
						$this->Order_model->updates($data,array("id"=>$item['id']));
						//当前订单是否使用积分
						if($item['integral']){
							$this->User_model->updates(array('integral'=>'-='.$item['integral']),array('id'=>$item['uid']));
							$this->Integral_model->add(array('uid'=>$item['uid'],'src'=>$item['gname'],'ands'=>'-','num'=>$item['integral'],'addtime'=>time()));
						}
						//当前订单商品是否有赠送积分
						$goods = $this->Goods_model->getItem(array('id'=>$item['gid']),'id,integral');
						if($goods['integral']){
							$this->User_model->updates(array('integral'=>'+='.$goods['integral']),array('id'=>$item['uid']));
							$this->Integral_model->add(array('uid'=>$item['uid'],'src'=>$item['gname'],'ands'=>'+','num'=>$goods['integral'],'addtime'=>time()));
						}
						//更新库存
						$this->Goods_model->updates(array('stock'=>"-=1"),array('id'=>$goods['id']));
					}else{
						set_Cache($order_no, $order_no);
					}
					return true;
				}else{
					log_message('error', $order_arr['return_msg'].$order_arr['err_code'].$order_arr['err_code_des'].': '.$total.':'.$order_no);
					return false;
				}
			}
		});
		$response->send(); 
		exit();
	}
	
	
	
}
